﻿using System;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMS.Web.Engine;
using CMS.Web.Data;

namespace CMS.Web.Controllers
{
    [ActionError(ViewName = "~/Hosts/Shared/Error.cshtml", Enabled = true)]   
    public class PageController : Controller
    {
        private IPagesRepository _pages;
        private IHostsRepository _hosts;

        public PageController(IPagesRepository pages, IHostsRepository hosts)
        {
            _pages = pages;
            _hosts = hosts;
        }

        public ActionResult Index(string path)
        {             
            IPageEntity page = _pages.GetPage(path, Request.Url.Host, Request.Url.Port);
            return View("~/Hosts/{0}/{1}".Args(page.Host, page.ViewName), page.Model);
        }

        [HttpPost]
        public ActionResult Index(string path, int? widget, FormCollection form)
        {
            IPageEntity page = _pages.GetPage(path, Request.Url.Host, Request.Url.Port);
            IWidget submittedWidget = page.Model.Widgets.Find(widget);

            if (!TryUpdateModel((dynamic)submittedWidget.Model, submittedWidget.Model.Prefix, form.ToValueProvider()))
                throw new Exception("Невозможно обновить модель {0}.".Args(submittedWidget.GetType()));

            submittedWidget.ProcessPost();            

            return View("~/Hosts/{0}/{1}".Args(page.Host, page.ViewName), page.Model);           
        }        
    }   
}